package main

import (
	"context"
	"fmt"
	"log"
	"net"

	"hello_server/pb"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
)

type server struct {
	pb.UnimplementedHelloServer
}

//确保server结构体实现了pb.HelloServer接口
// var _ pb.HelloServer = &server{}
var _ pb.HelloServer = (*server)(nil)


func (s *server) SayHello(ctx context.Context, in *pb.Request) (*pb.Response, error) {
	// 从客户端读取metadata.
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return nil, status.Errorf(codes.DataLoss, "UnarySayHello: failed to get metadata")
	}
	if t, ok := md["timestamp"]; ok {
		fmt.Printf("timestamp from metadata:\n")
		// []string
		for i, e := range t {
			fmt.Printf(" %d. %s\n", i, e)
		}
	}
	return &pb.Response{
		Reply: "hello " + in.Name,
	}, nil
}

func main() {
	lis, err := net.Listen("tcp", ":8081")
	if err != nil {
		log.Fatalf("net.Listen failed, err:%v\n", err)
	}

	s := grpc.NewServer()
	pb.RegisterHelloServer(s, &server{})

	// 程序启动之前 要注册服务到consul
	register2Consul()

	log.Println("server start...")
	if err := s.Serve(lis); err != nil {
		log.Fatalf("s.Serve failed, err:%v\n", err)
	}
}
